﻿using Reader.Core.Application;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Reader.Core
{
    public class Net
    {
        public async Task<Result> DownloadStreamToFileAsync(string url, string path)
        {
            using var result = await HttpClientHelper.GetAsync(url, ResultType.Stream);
            if (result.Success)
            {
                var filename = Path.GetFileName(url);
                if (!path.Contains(filename))
                {
                    path = Path.Combine(path, filename);
                }
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                await result.Stream.WriteFileStreamAsync(path);
                result.Stream.Close();
                result.Stream.Dispose();
                return ResultStatus.Success();
            }
            else
            {
                return ResultStatus.Fail(result.Message);
            }
        }
    }
}
